package com.ostrich.cloud.ostrichGoodsService.service.component;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.errorprone.annotations.Var;
import com.ostrich.cloud.ostrichGoodsSercice.model.Dto.GoodsDto;
import com.ostrich.cloud.ostrichGoodsService.infra.mapper.GoodsMapper;
import com.ostrich.cloud.ostrichGoodsService.infra.model.Goods;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.redisson.client.protocol.ScoredEntry;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class OstrichJob {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private GoodsMapper goodsMapper;

    @XxlJob("dayHotProduct")
    public List<Goods> dayHotProduct(){
        log.info("查询数据库商品");
        QueryWrapper<Goods> wrapper=new QueryWrapper<>();
        List<Goods> goods = goodsMapper.selectList(wrapper);
        if(goods==null||goods.size()==0){
            log.info("查询结果为空");
            return null;
        }
        log.info("查询完成{}",goods);

        RMap<Integer, Goods> goods1 = redissonClient.getMap("goods");
        Map<Goods,Double> map = new HashMap<>();

        for (Goods g:goods){
            log.info("从redis中查询昨天商品");
            Goods goods2 = goods1.get(g.getGoodsId());
            if(goods2!=null){
                log.info("计算今日实际销量：{}",goods2);
                int i = g.getSales() - goods2.getSales();
                log.info("添加到分数map{}",i);
                map.put( g,i + 0.0);
                log.info("添加到map成功{}",g);
            }
            log.info("把今日商品销量存入redis");
            goods1.put(g.getGoodsId(),g);
            log.info("今日商品存入成功");
        }
        goods1.expire(25, TimeUnit.HOURS);
        RScoredSortedSet<Goods> products = redissonClient.getScoredSortedSet("products");
        log.info("把今日实际销量存入redis：{}",map);
        products.addAll(map);
        products.expire(25, TimeUnit.HOURS);
        log.info("存入成功");

        log.info("获取排名");
        Collection<ScoredEntry<Goods>> scoredEntries = products.entryRangeReversed(0, 5);
        List<Goods> goods2 = new ArrayList<>();
        products.clear();
        for (ScoredEntry<Goods> s:scoredEntries){
            Goods value = s.getValue();
            if(value!=null){
                goods.add(value);
            }
        }
        log.info("获取成功{}",goods2);

        return goods2;
    }



}
